<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Konva 矩形拖动宽高</title>
  <script src="./konva.min.js"></script>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #f0f0f0;
    }

    #container {
      height: 100vh;
    }
  </style>
</head>

<body>
  <div id="container"></div>
  <script>
    var stage = new Konva.Stage({
      container: 'container',
      width: window.innerWidth,
      height: window.innerHeight
    })

    var layer = new Konva.Layer()
    stage.add(layer)

    var rect = new Konva.Rect({
      x: 140,
      y: 140,
      width: 100,
      height: 50,
      fill: 'red',
      draggable: true
    })
    layer.add(rect)

    var tr = new Konva.Transformer()
    layer.add(tr)
    tr.attachTo(rect)

    // 监听宽高变化
    rect.on('transform', function () {
      console.log('%c [ New width ]-53', 'font-size:13px; background:pink; color:#bf2c9f;', this.width() * this.scaleX())
      console.log('%c [ New height ]-54', 'font-size:13px; background:pink; color:#bf2c9f;', this.height() * this.scaleY())
      console.log('%c [  ]-55', 'font-size:13px; background:pink; color:#bf2c9f;',)
    })

    rect.on('transformend', function () {
      // 终止变换后固定scale，重新设置宽高
      var newWidth = this.width() * this.scaleX()
      var newHeight = this.height() * this.scaleY()
      // 重置宽高 计算scale后的宽高
      this.width(newWidth)
      this.height(newHeight)
      // 重置scale 实际宽高 防止scale影响宽高
      this.scaleX(1)
      this.scaleY(1)
      console.log('Final width:', newWidth)
      console.log('Final height:', newHeight)
    })

    layer.draw();
  </script>
</body>

</html>